package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmii.sjw.department.control.common.AccessTokenFetcher;
import com.cmii.sjw.department.control.jsc.mapper.SchoolMapMapper;
import com.cmii.sjw.department.control.jsc.model.SchoolInfo;
import com.cmii.sjw.department.control.jsc.service.SchoolInfoService;
import com.cmii.sjw.department.control.jsc.vo.SchoolInfoVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SchoolInfoServiceImpl extends ServiceImpl<SchoolMapMapper, SchoolInfo> implements SchoolInfoService {

    @Autowired
    private SchoolMapMapper schoolMapMapper;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();


    // 接口URL列表
    private final String apiUrls = "http://23.210.23.13:9000/edu-data-management/api/v1/broker/api/20";


    @Override
    public Map<String, List<String>> listSchool() {
        List<String> schoolLevels = schoolMapMapper.listBySchoolLevel();
        Map<String, List<String>> result = new HashMap<>();

        for (String schoolLevel : schoolLevels) {
            List<String> stageSubTypes = schoolMapMapper.listByStageSubType(schoolLevel);
            result.put(schoolLevel, stageSubTypes);
        }

        return result;
    }

    /**
     * 学校带坐标信息
     *
     * @return 数据入库
     */
    @Override
    public void saveData() {
        try {
            List<SchoolInfo> schoolInfoList = getValueFromApiWithTime(apiUrls);
            if (schoolInfoList != null && !schoolInfoList.isEmpty()) {
                // 清空表中的现有数据
                try {
                    schoolMapMapper.delete(null);
                    log.info("成功清空表中的现有数据");
                } catch (Exception e) {
                    log.error("清空表失败: {}", e.getMessage(), e);
                    return;
                }

                // 将结果保存到数据库
                for (SchoolInfo schoolInfo : schoolInfoList) {
                    try {
                        schoolMapMapper.insert(schoolInfo);
                        log.info("成功存入数据库: {}", schoolInfo.getName());
                    } catch (Exception e) {
                        log.error("存入失败: {}", e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("API调用失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 学校带坐标信息
     *
     * @return 首页展示
     */

    @Override
    public List<SchoolInfoVO> index() {
        List<SchoolInfoVO> schoolInfoVo = schoolMapMapper.countIndex();
        return schoolInfoVo;
    }

    private List<SchoolInfo> getValueFromApiWithTime(String baseUrl) {
        try {
            String accessToken = new AccessTokenFetcher().fetchAccessToken();
            log.info("使用的访问令牌: {}", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", accessToken);
            headers.setContentType(MediaType.APPLICATION_JSON);

            int page = 1;
            int pageSize = 10000;
            List<SchoolInfo> allSchools = new ArrayList<>();

                String url = baseUrl + "?page=" + page + "&pageSize=" + pageSize;
                HttpEntity<?> entity = new HttpEntity<>(headers);

                ResponseEntity<String> response = restTemplate.exchange(
                        url,
                        HttpMethod.GET,
                        entity,
                        String.class
                );

                if (response.getStatusCode().is2xxSuccessful()) {
                    String responseBody = response.getBody();
                    JsonNode jsonNode = objectMapper.readTree(responseBody);

                    JsonNode resultsNode = jsonNode.path("results");
                    if (resultsNode.isArray()) {
                        for (JsonNode resultNode : resultsNode) {
                            SchoolInfo schoolInfo = new SchoolInfo()
                                    .setId(resultNode.path("id").asInt())
                                    .setSchoolTypeCode(resultNode.path("school_type_code").asText())
                                    .setSchoolTypeName(resultNode.path("school_type_name").asText())
                                    .setName(resultNode.path("name").asText())
                                    .setAddress(resultNode.path("address").asText())
                                    .setEduTypeCode(resultNode.path("edu_type_code").asText())
                                    .setEduTypeName(resultNode.path("edu_type_name").asText())
                                    .setCompetentDeptCode(resultNode.path("competent_dept_code").asText())
                                    .setCompetentDept(resultNode.path("competent_dept").asText())
                                    .setBxTypeCode(resultNode.path("bx_type_code").asText())
                                    .setBxTypeName(resultNode.path("bx_type_name").asText())
                                    .setAdministrativeRegion(resultNode.path("administrative_region").asText())
                                    .setAreaCode(resultNode.path("area_code").asText())
                                    .setManagementAreaName(resultNode.path("management_area_name").asText())
                                    .setBaiduX(resultNode.path("baidu_x").asText())
                                    .setBaiduY(resultNode.path("baidu_y").asText())
                                    .setCgcsX(resultNode.path("cgcs_x").asText())
                                    .setCgcsY(resultNode.path("cgcs_y").asText())
                                    .setGdX(resultNode.path("gd_x").asText())
                                    .setGdY(resultNode.path("gd_y").asText())
                                    .setAddressMatching(resultNode.path("address_matching").asText())
                                    .setOrganizationCode(resultNode.path("organization_code").asText())
                                    .setNumFacsStaff(resultNode.path("num_facs_staff").asInt())
                                    .setStuCount(resultNode.path("stu_count").asInt())
                                    .setLandArea(resultNode.path("land_area").asInt())
                                    .setSchoolLevelCode(resultNode.path("school_level_code").asText())
                                    .setSchoolLevel(resultNode.path("school_level").asText())
                                    .setStageSubTypeCode(resultNode.path("stage_sub_type_code").asText())
                                    .setStageSubType(resultNode.path("stage_sub_type").asText())
                                    .setPhdPoint(resultNode.path("phd_point").asText());

                            allSchools.add(schoolInfo);
                        }
                        int totalCount = jsonNode.path("totalCount").asInt();
                        if (allSchools.size() >= totalCount) {

                        }

                        page++;
                    } else {
                        log.error("响应中未找到有效的结果: {}", responseBody);
                        throw new RuntimeException("响应中未找到有效的结果");
                    }
                } else {
                    log.error("HTTP 请求返回: {} {}", url, response.getStatusCodeValue());
                    throw new RuntimeException("API 请求返回状态码异常");
                }


            return allSchools;
        } catch (Exception e) {
            log.error("API调用失败 {}: {}", baseUrl, e.getMessage(), e);
            throw new RuntimeException("API 调用失败", e);
        }
    }
}
